<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
	<style>
		#box {
			width: 200px;
			height: 200px;
			background-color: #ccc;
			/* position: absolute;
			top: 0;
			left: 0; */
			transform: translate(0px, 0px);
		} 	
	</style>

</head>
<body>
	<div id="box"></div>
</body>

<script>
		let oBox = document.querySelector('#box');
		let disX,disY;
		let x = 0,y = 0;
		// 在touch事件中，没有ev.clientX，要用ev.targetTouches[0].clientX，因为touch事件要兼容多点触碰

		function fnMove(ev) {
			// oBox.style.left = ev.targetTouches[0].clientX - disX + 'px';
			// oBox.style.top = ev.targetTouches[0].clientY - disY + 'px';

			// transform的写法
			// 得出元素距离屏幕边缘的距离，也就是手指实时移动的距离
			x = ev.targetTouches[0].clientX - disX;
			y = ev.targetTouches[0].clientY - disY;
			oBox.style.transform = `translate(${x}px, ${y}px)`;
		}

		function fnEnd(ev) {
			oBox.removeEventListener('touchmove', fnMove, false);
			oBox.removeEventListener('touchend', fnEnd, false);
		}

		oBox.addEventListener('touchstart', function(ev) {
			// disX = ev.targetTouches[0].clientX - oBox.offsetLeft;
			// disY = ev.targetTouches[0].clientY - oBox.offsetTop;

			// transform的写法
			// 得出点击元素时，手指距离元素边缘的距离
			disX = ev.targetTouches[0].clientX - x;
			disY = ev.targetTouches[0].clientY - y;



			oBox.addEventListener('touchmove', fnMove, false)

			oBox.addEventListener('touchend', fnEnd, false)
		},false)


	</script>
</html>